python 将matplotlib绘制的图表赋给一个img对象 matplotlib输出图形到网页 | 您所在的位置:网站首页 › python matplotlib 输出网页 › python 将matplotlib绘制的图表赋给一个img对象 matplotlib输出图形到网页 |
Python最常用的绘图库,提供了一整套十分适合交互式绘图的命令 API,比较方便的就可以将其嵌入到GUI应用程序中。 官网:https://matplotlib.org/ 学习方式:从官网examples入门学习: https://matplotlib.org/examples/index.html https://matplotlib.org/gallery.html 1.Matplotlib 是一个非常强大的 Python 画图工具.。 2.手中有很多数据, 可是不知道该怎么呈现这些数据.,Matplotlib它能帮你画出美丽的: 线图; 散点图; 等高线图; 条形图; 柱状图; 3D 图形, 甚至是图形动画等等 基本使用设置在jupyter中matplotlib的显示情况: 1.%matplotlib tk 在GUI中显示。 2.%matplotlib inline 在行内显示。 figurefigure:图形,matplotlib中的所有图像都是位于figure对象中,一个图像只能 有一个figure对象。matplotlib 的 figure 就是一个 单独的 figure 小窗口, 小窗口 里面还可以有更多的小图片.。 import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import pandas as pd # 设置中文显示 mpl.rcParams['font.sans-serif'] = ['SimHei'] mpl.rcParams['axes.unicode_minus'] = False data = np.arange(-3,3,0.1) x = np.sin(data) y = np.cos(data) # 画图 ''' figsize:图形的大小 facecolor:边框的背景颜色 ''' # plt.figure(frameon=False,facecolor='green') # plt.plot(data,x,) # 第一个线图 # # plt.figure(figsize = (8,6)) # plt.plot(data,y) # 第二个线图 # # plt.figure(facecolor='red') # plt.plot(data,x,) # 第三个线图第一条线 # plt.plot(data,y) # 第三个线图第二条线 plt.figure(facecolor='red') plt.plot(data,x,data,y) # 不常见 plt.plot(x) # 如果只有一个参数这个参数 默认是Y轴的数据,X默认是从 0 - n # plt.axis('off') plt.show()颜色、标记和线型plot(x,y,color='red', linestyle='dashed', marker='o'.....)。 绘图中用到的直线属性包括: (1)LineStyle:线形。 (2)LineWidth:线宽。 (3)Color:颜色。 (4)Marker:标记点的形状。 (5)label:用于图例的标签。 import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import pandas as pd # 设置中文显示 mpl.rcParams['font.sans-serif'] = ['SimHei'] mpl.rcParams['axes.unicode_minus'] = False data = np.arange(-3,3,0.1) x = np.sin(data) y = np.cos(data) plt.figure() # plt.plot(x,y,color = 'y') # 设置颜色 # plt.plot(x,y,color = 'y',linestyle = '--') # plt.plot(x,y,color = 'y',linestyle = '--',linewidth = 5,marker = '*',markersize = 20) # plt.plot(x,y,color = 'y',linestyle = '--',marker = 'o',label = 'x-line') plt.plot(x,y,'*b--',label = 'x-line',markersize=20) # 简写方式 plt.legend(loc='lower right') plt.axis('off') plt.show()线型: ''' '-' solid line style '--' dashed line style(线虚) '-.' dash-dot line style ':' dotted line style(点虚) '''market: https://matplotlib.org/api/markers_api.html View text 颜色: https://matplotlib.org/users/colormaps.html https://matplotlib.org/examples/color/colormaps_reference.html 由其文档可知,在 colormap 类别上,有如下分类: perceptual uniform sequential colormaps:感知均匀的序列化 colormapsequential colormaps:序列化(连续化)色图 colormap;gray:0-255 级灰度,0:黑色,1:白色,黑底白字;gray_r:翻转 gray 的显示,如果 gray 将图像显示为黑底白字,gray_r 会将其显示为白底黑字;binarydiverging colormaps:两端发散的色图 colormaps;seismicqualitative colormaps:量化(离散化)色图;miscellaneous colormaps:其他色图;rainbow获取色标 自定义色标 颜色的十六进制表示 显示plt.colormap的所有色标 刻度、标题、标签和图例legend ():生成默认图例, matplotlib 中的 legend 图例就是为了帮我们展示出 每个数据对应的图像名称. 更好的让读者认识到你的数据结构.。 xlabel、ylabel:设置X轴Y轴标签。 title:设置标题。 xlim、ylim:控制图标的范围。 xticks、yticks: 控制图标的刻度。 gca获取当前坐标轴信息。使用spines设置边框,使用set_color设置边框颜色: 默认白色。 解决中文显示问题: mpl.rcParams['font.sans-serif'] = ['SimHei'] mpl.rcParams['axes.unicode_minus'] = False import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import pandas as pd # 设置中文显示 mpl.rcParams['font.sans-serif'] = ['SimHei'] mpl.rcParams['axes.unicode_minus'] = False data = np.arange(-3,3,0.1) x = np.sin(data) y = np.cos(data) # 创建图形 fig = plt.figure() # 画图 plt.plot(x,y,'r--',label = 'x-line') # 生成图例 plt.legend(loc='upper left') #如果没有loc参数则是自动适应 # plt.legend(loc='lower right') #如果没有loc参数则是自动适应 #设置标题 plt.title('进球数') # 设置x/y轴标签 plt.xlabel('x轴') plt.ylabel('y轴') # 设置刻度的范围 # plt.xlim(1,10) # plt.ylim(1,10) # 设置图标的刻度 plt.xticks(np.arange(1,6,1),['中国','2月','3月','4月','5月']) # plt.xticks(np.arange(1,6,1),[str(i)+'月' for i in range(1,6,1)]) plt.yticks(np.arange(1,10)) #写入文本 plt.text(2,6,'这是一个练习图') #相对于坐标轴 fig.text(0.5,0.5,'this is test') #相对于画布 # 说明: # plt.text()依次传入坐标和字符串内容 # x,y 代表传入柱的位置和高度 # '%.2f' 代表传入字符串的内容 # ha='center' 设置文字水平对齐方式,其他参数查看帮助文档 # va='bottom' 设置文字垂直对齐方式,其他参数查看帮助文档 # size 设置字体大小 # 获取坐标轴信息 ax = plt.gca() ax.spines['right'].set_color(None) ax.spines['top'].set_color(None) # ax.spines['left'].set_color(None) # ax.spines['bottom'].set_color(None) # plt.axis('off') # 展示图片 plt.show()loc参数的可选值 设置坐标轴 # Annotation 标注 # 画出基本图 #当图线中某些特殊地方需要标注时,我们可以使用 annotation. matplotlib 中的 annotation 有两种方法, #一种是用 plt 里面的 annotate,一种是直接用 plt 里面的 text 来写标注. '''首先,我们在坐标轴中绘制一条直线.''' import matplotlib.pyplot as plt import numpy as np x = np.linspace(-3, 3, 50) y = 2*x + 1 plt.figure(num=1, figsize=(8, 5),) plt.plot(x, y,) '''移动坐标''' #使用plt.gca获取当前坐标轴信息. 使用.spines设置边框:右侧边框;使用.set_color设置边框颜色:默认白色; 使用.spines设置边框:上边框;使用.set_color设置边框颜色:默认白色; ax = plt.gca() ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') #然后我们挪动坐标轴的位置.使用.xaxis.set_ticks_position设置x坐标刻度数字或名称的位置:bottom.(所有位置:top,bottom,both,default,none) ax.xaxis.set_ticks_position('bottom') #使用.spines设置边框:x轴;使用.set_position设置边框位置:y=0的位置;(位置所有属性:outward,axes,data) ax.spines['bottom'].set_position(('data', 0)) #使用.yaxis.set_ticks_position设置y坐标刻度数字或名称的位置:left.(所有位置:left,right,both,default,none) ax.yaxis.set_ticks_position('left') #使用.spines设置边框:y轴;使用.set_position设置边框位置:x=0的位置;(位置所有属性:outward,axes,data) ax.spines['left'].set_position(('data', 0)) '''标注出点(x0, y0)的位置信息.''' x0 = 1 y0 = 2*x0 + 1 plt.plot([x0, x0,], [0, y0,], 'k--', linewidth=2.5) plt.scatter([x0, ], [y0, ], s=50, color='b') '''添加注释 annotate''' # 其中参数xycoords='data' 是说基于数据的值来选位置, xytext=(+30, -30) 和 textcoords='offset points' 对于标注位置的描述 和 xy 偏差值, arrowprops是对图中箭头类型的一些设置. plt.annotate(r'$2x+1=%s$' % y0, xy=(x0, y0), xycoords='data', xytext=(+30, -30), textcoords='offset points', fontsize=16, arrowprops=dict(arrowstyle='->', connectionstyle="arc3,rad=.2")) '''添加注释 text ''' plt.text(-3.7, 3, r'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$',fontdict={'size': 16, 'color': 'r'}) plt.show()View Code import math import matplotlib as mpl import matplotlib.pyplot as plt import mpl_toolkits.axisartist as axisartist # 设置中文显示 mpl.rcParams['font.sans-serif'] = ['SimHei'] mpl.rcParams['axes.unicode_minus'] = False # 创建画布 fig = plt.figure(figsize=(16, 8)) # 使用axisartist.Subplot方法创建一个绘图区对象ax ax = axisartist.Subplot(fig, 111) # 将绘图区对象添加到画布中 fig.add_axes(ax) # 通过set_visible方法设置绘图区所有坐标轴隐藏 ax.axis[:].set_visible(False) # ax.new_floating_axis代表添加新的坐标轴 ax.axis["x"] = ax.new_floating_axis(0, 0) # 第一个0表示水平线,第二个0表示经过0点。 # 给x坐标轴加上箭头 ax.axis["x"].set_axisline_style("->", size=1.0) # ->表示虚心箭头,size表示箭头的大小。 # 添加y坐标轴,且加上箭头 ax.axis["y"] = ax.new_floating_axis(1, 0) # 1表示竖线,第二个0表示经过0点。 ax.axis["y"].set_axisline_style("-|>", size=1.0) # -|>表示虚心箭头,size表示箭头的大小。 # 设置x、y轴上刻度显示方向 ax.axis["x"].set_axis_direction("top") ax.axis["y"].set_axis_direction("right") x = [i / 10 for i in range(-100, 101)] y = [math.sin(i) for i in x] plt.plot(x, y, '-b', label='y=sin(x)') y1 = [2 ** i for i in x] plt.plot(x, y1, '-k', label='y=2^x') x2 = [i / 10 for i in range(1, 101)] y2 = [math.log(i, 2) for i in x2] plt.plot(x2, y2, '-r', label='y=log2x') plt.plot(x, x, '-g', label='y=x') # 生成图例 plt.legend(loc='lower right') # 设置x轴和y轴的取值范围 plt.xlim(-10, 10) plt.ylim(-10, 10) # 设置x轴和y轴标签名 plt.xlabel('x轴') plt.ylabel('y轴') # 设置显示网格 plt.grid(True) plt.show()tick 能见度 #当图片中的内容较多,相互遮盖时,我们可以通过设置相关内容的透明度来使图片更易于观察,也即是通过本节中的bbox参数设置来调节图像信息. import matplotlib.pyplot as plt import numpy as np x = np.linspace(-3, 3, 50) y = 0.1*x plt.figure() # 在 plt 2.0.2 或更高的版本中, 设置 zorder 给 plot 在 z 轴方向排序 plt.plot(x, y, linewidth=10, zorder=1) plt.ylim(-2, 2) ax = plt.gca() ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.spines['bottom'].set_position(('data', 0)) ax.yaxis.set_ticks_position('left') ax.spines['left'].set_position(('data', 0)) '''然后对被遮挡的图像调节相关透明度,本例中设置 x轴 和 y轴 的刻度数字进行透明度设置''' #中label.set_fontsize(12)重新调节字体大小,bbox设置目的内容的透明度相关参,facecolor调节 box 前景色,edgecolor 设置边框, 本处设置边框为无,alpha设置透明度. for label in ax.get_xticklabels() + ax.get_yticklabels(): label.set_fontsize(12) # 在 plt 2.0.2 或更高的版本中, 设置 zorder 给 plot 在 z 轴方向排序 label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.7, zorder=2)) # label.set_bbox(dict(facecolor='red', edgecolor='None', alpha=0.7, zorder=2)) print(ax.get_xticklabels()+ ax.get_yticklabels()) plt.show()Subplot 子图subplot:子图,figure对象下创建一个或多个subplot对象(即axes) 用于绘制图像。 subplot(numRows, numCols, plotNum)。 x1 = [1,3,5] y1 = [2,4,5] x2 = [1,4,5] y2 = [3,2,5] # 创建图形 plt.figure() plt.subplot(221) plt.plot(x1,y1,'r--') plt.subplot(223) plt.plot(x2,y2,'b-') plt.show()Sublots():返回一个图像和多个子图。 参数: nrows=x, ncols=x, sharex=True, sharey=False, gridspec_kw={'height_ratios':[2,2,1,1]} 例: fig, ax = plt.subplots(2,2),其中参数分别代表子图的行数和列数,一共有 2x2 个图像。函数返回 一个figure图像和一个子图ax的array列表。 # 生成一个figure 以及子图的列表 fig, ax = plt.subplots(2,2) # 2行 2列 2维列表 for i in range(2): for j in range(2): ax[i][j].plot(np.random.randn(50).cumsum(),'r--') # ax[i,j].plot(np.random.randn(50).cumsum(),'r--') fig, ax = plt.subplots(2,2) # 2行 2列 2维列表 colors=['Reds','Blues'] for i in range(2): for j in range(2): ax1=ax[i][j].scatter(np.random.randn(50).cumsum(),np.random.randn(50),c=np.random.randn(50),cmap=colors[i]) fig.colorbar(ax1,ax=ax[i][j]) #参数mappable理解起来就是我们需要提供一个可以映射颜色的对象,这个对象就是我们作的图,参数ax用来指示colorbar()获取到的渐变色条在哪里显示,ax参数设置成多个Axes对象。 plt.show() '''图像保存''' plt.savefig('zitu.jpg')子图面向对象的形式: fig = plt.figure() #Figure实例,可以添加Axes实例。 ax = fig.add_subplot(111) #返回Axes实例 参数1,子图的总行数 参数2,子图的总列数 参数3,子图位置 在Figure上添加子图的常用方法。# 创建图形 fig= plt.figure() fig.suptitle('运行效果') #设置总标题 ax1 = fig.add_subplot(321,facecolor='b') #添加子图背景颜色 ax1.plot(np.random.randn(50).cumsum(),'r--') plt.title('this is test') ax2 = fig.add_subplot(322,facecolor='r') ax2.plot(np.random.randn(50).cumsum(),'b-') plt.title('这是一个测试') ax3 = fig.add_subplot(312) ax3.plot(np.random.randn(50).cumsum(),'y--') ax4 = fig.add_subplot(325) ax4.plot(np.random.randn(50).cumsum(),'g-') ax4.set_title('this is test') ax5 = fig.add_subplot(326) ax5.plot(np.random.randn(50).cumsum(),'g-') ax5.set_title('这是一个测试') plt.show()利用subplot_adjust()函数可以对画的多个子图进行调整,优化间隔,它一共有left、right, bottom, top, wspace, hspase 六个参数,取 值从0至1。 # 创建图形 fig= plt.figure(figsize=(10,10)) #设置总标题 # fig.suptitle('运行效果') plt.suptitle('运行结果') ax1 = fig.add_subplot(221,facecolor='b') #添加子图背景颜色 ax1.plot(np.random.randn(50).cumsum(),'r--') plt.title('this is test') ax2 = fig.add_subplot(222,facecolor='r') ax2.plot(np.random.randn(50).cumsum(),'b-') plt.title('这是一个测试') ax3 = fig.add_subplot(223) ax3.plot(np.random.randn(50).cumsum(),'y--') ax5 = fig.add_subplot(224) ax5.plot(np.random.randn(50).cumsum(),'g-') fig.subplots_adjust(wspace=0,hspace=0) plt.show() #画了多个子图时,在保存的时候出现了以下问题,就是子图之间有重叠。这种情况发生在我调用函数画图后,函数返回一个fig对象(fig=plt.gcf()),利用下面这行: # plt.savefig(savefig_path, bbox_inches='tight', dpi=300) #bbox_inches='tight'帮助删除图片空白部分共用x轴 import numpy as np import matplotlib.pyplot as plt t = np.arange(0.01, 10.0, 0.01) data1 = np.exp(t) data2 = np.sin(2 * np.pi * t) fig, ax1 = plt.subplots() color = 'tab:red' ax1.set_xlabel('time (s)') ax1.set_ylabel('exp', color=color) ax1.plot(t, data1, color=color) ax1.tick_params(axis='y', labelcolor=color) ax2 = ax1.twinx() color = 'tab:blue' ax2.set_ylabel('sin', color=color) ax2.plot(t, data2, color=color) ax2.tick_params(axis='y', labelcolor=color) plt.xticks(rotation=50) #如果不是共用轴,就可以设置。现在共用X轴就无法使用xticks的rotation来对x周标签旋转 fig.tight_layout() plt.show()常用图形柱状图matplotlib.pyplot. bar (*args, **kwargs) bar(left, height, width, bottom, * args, align='center', **kwargs)。 参数: left:数据标量。 height:高。 width:款。 bottom:底端对应Y轴。 align:对齐如果为 "居中", 则将x参数解 释为条形中心的坐标。如果 "边缘", 将条形按其左边缘对齐要对齐右边缘的条形图, 可传递负的宽度和对 align='edge' import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import pandas as pd # 设置中文显示 mpl.rcParams['font.sans-serif'] = ['SimHei'] mpl.rcParams['axes.unicode_minus'] = False # 设置jupyter中 的显示方式 # %matplotlib tk %matplotlib inline # 设置数据 height = np.array([100,200,300,400]) # y # 设置数据标量 left = np.arange(1,5,1) # 4 x # 设置柱子宽度 n = 4 width = 0.8/4 # 创建figure plt.figure() # 画图 plt.bar(left,height,width = width,color = 'lightskyblue',align = 'center',label = '上海') plt.bar(left-width,height+20,width = width,color = 'red',align = 'center',label = '北京') plt.bar(left+width,height+10,width = width,color = 'yellowgreen',align = 'center',label = '深圳') # 生成图例 plt.legend(loc='upper left') #设置标题 plt.title('旅游人数') #要改 # 设置x/y轴标签 # 要改 plt.xlabel('月份') plt.ylabel('人次/百万') # 设置图标的刻度 plt.xticks(np.arange(1,5,1),['1月','2月','3月','4月']) # 要改 # plt.xticks(np.arange(1,6,1),[str(i)+'月' for i in range(1,6,1)]) plt.yticks(np.arange(100,600,100)) # 获取坐标轴信息 ax = plt.gca() ax.spines['right'].set_color(None) ax.spines['top'].set_color(None) # 展示图片 plt.show()# 设置画板大小 plt.figure(figsize=(10, 6)) # 画出柱状图 plt.barh(left, height, 0.5, color=['r', 'g', 'b','y']) plt.show()直方图matplotlib.pyplot.hist( x,bins=10,range=None,normed=False,weights=None,cumulative=False,bottom=None, histtype='bar', align='mid',orientation=u'vertical', rwidth=None, log=False,color=None, label=None,stacked=False,hold=None,**kwargs) 。 -- x: 一个列表或者多个列表(表示不同数据集,长度可以不一致)。 – range: 元组 – weights: x里每个元素对bin高度的贡献(默认为1)。 – bottom: 数字或者长度为bins的列表。 – histtype: ['bar' | 'barstacked' | 'step' | 'stepfilled']。 – align: ['left' | 'mid' | 'right']。 – orientation: ['horizontal' | 'vertical']。 – rwidth: bar相对bin的宽度。 – color: 一种颜色或者颜色列表(针对不同数据集)。 import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import pandas as pd # 设置中文显示 mpl.rcParams['font.sans-serif'] = ['SimHei'] mpl.rcParams['axes.unicode_minus'] = False # 设置jupyter中 的显示方式 # %matplotlib tk %matplotlib inline # 设置数据 mu , sigma = 100,15 # x = np.random.randn(10000)*mu*sigma x = np.random.randn(10000).cumsum() plt.figure() plt.hist(x,1000,alpha = 0.5,color = 'red') plt.title('频率图') plt.grid(True) plt.show()散点图matplotlib.pyplot. scatter (x, y, s=none, c=none, marker=none, cmap= None, norm=none, vmin=none, vmax=none, alpha=none, Linewidths=none, verts=none, edgecolors=none, hold=none, data= None, **kwargs)。 参数: x,y:相同长度的数组序列。 s :散点的大小标量或形同数组,可选参数,默认20。 c :散点的色彩或颜色序列,可选。 maker:标记风格,可选,默认是‘o’。 norm:数据的亮度。 alpha:散点的透明度 import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import pandas as pd # 设置中文显示 mpl.rcParams['font.sans-serif'] = ['SimHei'] mpl.rcParams['axes.unicode_minus'] = False # 设置jupyter中 的显示方式 # %matplotlib tk %matplotlib inline # 设置数据 x = np.random.randn(1000) y = np.random.randn(1000) plt.scatter(x,y,c = np.random.rand(1000,4),s = np.random.rand(1000)*50,alpha = 0.7) plt.title('aaa') plt.show()饼图matplotlib.pyplot. pie(x, explode=None, labels=None, colors=('b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'), autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None, radius=None, counterclock=True, wedgeprops=None, textprops=None, center = (0, 0), frame = False ) 参数: x (每一块)的比例,如果sum(x) > 1会使用sum(x)归一化。 labels (每一块)饼图外侧显示的说明文字。 explode (每一块)离开中心距离。 startangle 起始绘制角度,默认图是从x轴正方向逆时针画起,如设定=90则从y轴正方向画起。 shadow 是否阴影。 labeldistance label绘制位置,相对于半径的比例, 如 |
CopyRight 2018-2019 实验室设备网 版权所有 |